/**
 * Created by wangfei on 2017/6/23.
 */
requirejs.config({
    baseUrl: '../../',
    paths:  {
        avalon: 'javascript/avalon.min',
        jquery: 'js/plugins/jquery/jquery-2.1.1.min',
        navPage: 'nav-page',
        bootstrap: 'js/plugins/bootstrap/bootstrap.min',
        select2: 'js/plugins/select2/select2',
        config: 'javascript/config',
        api: 'javascript/api',
        layer: 'js/plugins/layer1/layer',
        arg: 'javascript/arg',
		ckeditor: 'js/plugins/ckeditor/ckeditor',
		cookie: 'javascript/base'
    },
    shim: {
        'select2':{
            deps: ['jquery']
        },
        'bootstrap':{
            deps: ['jquery']
        },
        api: {
            deps: ['jquery']
        },
        layer: {
            deps: ['jquery']
        }
    }
});


(function(win, dom, requirejs, initVm){
    var vm;
    requirejs(['avalon', 'jquery', 'navPage','bootstrap','select2', 'config', 'api', 'layer', 'arg', 'ckeditor', 'cookie'], function(){
        //初始化vm
        vm = initVm(dom);
    });
    function inputChange(obj) {
        //vm.images.push(window.URL.createObjectURL(obj.files[0]) || obj.value);
		var file = obj.files[0];
		var url = URL.createObjectURL(file);
		var form = new FormData();
		form.append('imgFile', file);
		var idx = parseInt(obj.id.split('updateIMage')[1]);
		var images = vm.images;
		Api.sendImg(form, function(resp) {
			if(resp.code == 0) {
				vm.images.splice(idx, 1, resp.data);
			} else {
				layer.msg(resp.msg);
			}
		});
    }
    win.inputChange = inputChange;
	function ckeditorImgChange(editorName, obj) {
		var file = obj.files[0];
		var url = URL.createObjectURL(file);
		var form = new FormData();
		form.append('imgFile', file);
		Api.sendImg(form, function(resp) {
			if(resp.code == 0) {
				CKEDITOR.instances[editorName].insertHtml('<img src="'+resp.data+'">');
			} else {
				layer.msg(resp.msg);
			}
		});
	}
	win.ckeditorImgChange = ckeditorImgChange;
})(window, document, requirejs, function(dom){
    var vm = avalon.define({
        $id:'container',
        currentPage: 'page1',
        changePage: function(page){
            vm.currentPage = page;
        },
        images: new Array(5),
		/**
			上传图片下标
		*/
		openFile: function(index){
			
		},
		deleteImage: function(imgUrl) {
			layer.confirm('你确定要删除吗？', function(index) {
				var idx = -1;
				for(var i=0;i<vm.images.length;i++) {
					if(vm.images[i] == imgUrl) {
						idx = i;
						vm.images.splice(i, 1, null);
						break;
					}
				}
				Api.wareDeleteImg({imgurl: imgUrl}, function(resp) {
					layer.msg(resp.msg);
				})
				layer.close(index);
			});
		},
		categoryList: [],
		wareCategoryList: function(siteId) {
			Api.wareCategoryList({saleSiteId: siteId}, function(resp) {
				if(resp.code == 0) {
					vm.categoryList = resp.data;
				} else {
					layer.msg(resp.msg);
				}
			});
		},
		brandList: [],
		wareBrandList: function() {
			Api.wareBrandList(function(resp) {
				if(resp.code == 0) {
					vm.brandList = resp.data;
				} else {
					layer.msg(resp.msg);
				}
			});
		},
		unitList: [],
		wareUnitList: function() {
			Api.wareUnitList(function(resp) {
				if(resp.code == 0) {
					vm.unitList = resp.data;
				} else {
					layer.msg(resp.msg);
				}
			});
		},
		siteList: [],
		supplierSiteList: function() {
			Api.supplierSiteList(function(resp) {
				if(resp.code == 0) {
					vm.siteList = resp.data;
				} else {
					layer.msg(resp.msg);
				}
			});
		},
		provinceList: [],
		regionProvinceList: function() {
			Api.regionProvinceList(function(resp) {
				if(resp.code == 0) {
					vm.provinceList = resp.data;
				} else {
					layer.msg(resp.msg);
				}
			});
		},
		cityList: [],
		regionCityList: function(pId) {
			Api.regionCityList({parentId: pId}, function(resp) {
				if(resp.code == 0) {
					vm.cityList = resp.data;
				} else {
					layer.msg(resp.msg);
				}
			});
		},
		params: {},
		form: {
			id: '',
			categoryId: '',
			categoryName: '',
			brandId: '',
			brandName: '',
			code: '',
			barcode: '',
			name: '',
			wareDes: '',
			pricePiece: '',
			priceUnit: '',
			unitId: '',
			unitName: '',
			numberPerBox: '',
			netContent: '',
			weightPiece: '',
			saleSiteId: '',
			saleSiteName: '',
			sendProvinceId: '',
			sendProvinceName: '',
			sendCityId: '',
			sendCityName: '',
			numberWholesale: '',
			numberInventory: '',
			imageMain: '',
			imageThumb: '',
			productionLicense: '',
			performStandard: '',
			shelfLife: '',
			methodStorage: '',
			methodPacking: '',
			sizePiece: '',
			dateManufacture: '见包装封口处',
			producingArea: '',
			manufacturer: '',
			description: '',
			wareAttrList: [],
			wareStockWarn: {
				threshold: '',
				noticeMobile: ''
			}
		},
		bindStatus: 0,
		wareGetId: function(wareId) {
			Api.wareGetId(function(resp) {
				if(resp.code == 0) {
					vm.form.id = resp.data;
				} else {
					layer.msg(resp.msg);
				}
			});
		},
		historyBack: function() {
			history.back();
		},
		addDrafts: function() {
			vm.handlerFormData();
			Api.wareAddDrafts(vm.form, function(resp) {
				if(resp.code == 0) {
					layer.alert(resp.msg, function() {
						vm.historyBack();
					});
				} else {
					layer.msg(resp.msg);
				}
			});
		},
		addSubmit: function() {
			vm.handlerFormData();
			var result = vm.checkSubmit();
			if(result) {
				Api.wareAddSubmit(vm.form, function(resp) {
					if(resp.code == 0) {
						layer.alert(resp.msg, function() {
							vm.historyBack();
						});
					} else {
						layer.msg(resp.msg);
					}
				});
			}
		},
		checkSubmit: function() {
			if(vm.form.categoryId == null || vm.form.categoryId == '') {
				layer.alert('商品类别为空');
				return false;
			}
			if(vm.form.brandId == null || vm.form.brandId == '') {
				layer.alert('商品类别为空');
				return false;
			}
			if(vm.form.barcode == null || vm.form.barcode == '') {
				layer.alert('商品条码为空');
				return false;
			}
			if(vm.form.name == null || vm.form.name == '') {
				layer.alert('商品名称为空');
				return false;
			}
			if(vm.form.pricePiece == null || vm.form.pricePiece == '') {
				layer.alert('件装价格为空');
				return false;
			}
			if(vm.form.priceUnit == null || vm.form.priceUnit == '') {
				layer.alert('单价为空');
				return false;
			}
			if(vm.form.unitId == null || vm.form.unitId == '') {
				layer.alert('单装单位为空');
				return false;
			}
			if(vm.form.numberPerBox == null || vm.form.numberPerBox == '') {
				layer.alert('件规为空');
				return false;
			}
			if(vm.form.netContent == null || vm.form.netContent == '') {
				layer.alert('净含量为空');
				return false;
			}
			if(vm.form.weightPiece == null || vm.form.weightPiece == '') {
				layer.alert('件重量为空');
				return false;
			}
			if(vm.form.saleSiteId == null || vm.form.saleSiteId == '') {
				layer.alert('销售站点为空');
				return false;
			}
			if(vm.form.sendProvinceId == null || vm.form.sendProvinceId == '') {
				layer.alert('发货地为空');
				return false;
			}
			if(vm.form.sendCityId == null || vm.form.sendCityId == '') {
				layer.alert('发货地为空');
				return false;
			}
			if(vm.form.numberWholesale == null || vm.form.numberWholesale == '') {
				layer.alert('起批数量为空');
				return false;
			}
			if(vm.form.numberInventory == null || vm.form.numberInventory == '') {
				layer.alert('库存数量为空');
				return false;
			}
			if(vm.form.barcode.length > 20) {
				layer.alert('商品条码超长');
				return false;
			}
			if(vm.form.name.length > 30) {
				layer.alert('商品名称超长');
				return false;
			}
			if(vm.form.wareDes.length > 50) {
				layer.alert('商品描述超长');
				return false;
			}
			if(vm.images[0] == null || vm.images[0] == '') {
				layer.alert('商品主图未上传');
				return false;
			}
			return true;
		},
		handlerFormData: function() {
			vm.form.pricePiece = vm.form.priceUnit * vm.form.numberPerBox;
			vm.form.imageMain = vm.images.join(',');
			vm.form.categoryName = $('#categoryId').find('option:selected').text();
			vm.form.unitName = $('#unitId').find('option:selected').text();
			vm.form.sendProvinceName = $('#sendProvinceId').find('option:selected').text();
			vm.form.sendCityName = $('#sendCityId').find('option:selected').text();
			vm.form.brandId = $('#brandId').val();
			vm.form.brandName = $('#brandId').find('option:selected').text();
			/*
			var saleSiteId = $('#saleSiteId').val();
			if(typeof(saleSiteId) == 'string') {
				vm.form.saleSiteId = $('#saleSiteId').val();
				vm.form.saleSiteName = $('#saleSiteId').find('option:selected').text()
			} else if(saleSiteId instanceof Array) {
				vm.form.saleSiteId = $('#saleSiteId').val().join(',');
				var siteMap = {};
				for(var i=0;i<vm.siteList.length;i++) {
					siteMap[vm.siteList[i].id] = vm.siteList[i].name;
				}
				var saleSiteIdArr = vm.form.saleSiteId.split(',');
				var saleSiteNameArr = [];
				for(var i=0;i<saleSiteIdArr.length;i++) {
					saleSiteNameArr.push(siteMap[saleSiteIdArr[i]]);
				}
				vm.form.saleSiteName = saleSiteNameArr.join(',');
			}
			*/
			vm.form.description = CKEDITOR.instances.description.getData();
			
			var attrWareIds = [];
			var attrNames = [];
			for(var i=0;i<vm.form.wareAttrList.length;i++) {
				var attr = vm.form.wareAttrList[i];
				if(attr.wareId != '' && attr.name != '') {
					attrWareIds.push(attr.wareId);
					attrNames.push(attr.name);
				}
			}
			vm.form.attrWareIds = attrWareIds.join(",");
			vm.form.attrNames = attrNames.join(",");
			vm.form.threshold = vm.form.wareStockWarn.threshold;
			vm.form.noticeMobile = vm.form.wareStockWarn.noticeMobile;
		},
		addAttr: function() {
			vm.form.wareAttrList.push({wareId: '', name: ''});
		},
		removeAttr: function(index) {
			vm.form.wareAttrList.splice(index, 1);
		},
		wareErpGet: function() {
			Api.wareErpGet(vm.form, function(resp) {
				if(resp.code == 0) {
					//vm.form = resp.data;
					layer.confirm('你确定要覆盖？', function(index) {
						vm.form.code = resp.data.code;
						vm.form.barcode = resp.data.barcode;
						vm.form.name = resp.data.name;
						vm.form.pricePiece = resp.data.pricePiece;
						vm.form.priceUnit = resp.data.priceUnit;
						//vm.form.unitName = resp.data.unitName;
						for(var i=0;i<vm.unitList.length;i++) {
							var unit = vm.unitList[i];
							if(unit.name == resp.data.unitName) {
								vm.form.unitId = unit.id;
								vm.form.unitName = resp.data.unitName;
								$("#unitId").val(vm.form.unitId);
								break;
							}
						}
						vm.form.numberPerBox = resp.data.numberPerBox;
						vm.form.netContent = resp.data.netContent;
						vm.form.weightPiece = resp.data.weightPiece;
						vm.form.numberInventory = resp.data.numberInventory;
						vm.form.productionLicense = resp.data.productionLicense;
						vm.form.performStandard = resp.data.performStandard;
						vm.form.shelfLife = resp.data.shelfLife;
						vm.form.methodStorage = resp.data.methodStorage;
						vm.form.methodPacking = resp.data.methodPacking;
						vm.form.sizePiece = resp.data.sizePiece;
						vm.form.producingArea = resp.data.producingArea;
						vm.form.manufacturer = resp.data.manufacturer;
						vm.form.manufacturerAddress = resp.data.manufacturerAddress;
						layer.close(index);
					})
				} else {
					layer.msg(resp.msg);
				}
			});
		},
		showErp: false,
		supplierErp: function() {
			Api.supplierErp(function(resp) {
				if(resp.code == 0) {
					vm.showErp = resp.data;
				}
			});
		}
    })
	vm.$watch("form.sendProvinceId", function (pId) {
		vm.regionCityList(pId);
	})
    $("#brandId").select2({});
    $("#saleSiteId").select2({});
	$("#saleSiteId").on("change", function(e) {
		var saleSiteId = $('#saleSiteId').val();
		if(typeof(saleSiteId) == 'string') {
			vm.form.saleSiteId = $('#saleSiteId').val();
			vm.form.saleSiteName = $('#saleSiteId').find('option:selected').text()
		} else if(saleSiteId instanceof Array) {
			vm.form.saleSiteId = $('#saleSiteId').val().join(',');
			var siteMap = {};
			for(var i=0;i<vm.siteList.length;i++) {
				siteMap[vm.siteList[i].id] = vm.siteList[i].name;
			}
			var saleSiteIdArr = vm.form.saleSiteId.split(',');
			var saleSiteNameArr = [];
			for(var i=0;i<saleSiteIdArr.length;i++) {
				saleSiteNameArr.push(siteMap[saleSiteIdArr[i]]);
			}
			vm.form.saleSiteName = saleSiteNameArr.join(',');
		}
		vm.wareCategoryList(vm.form.saleSiteId);
	});
	CKEDITOR.replace('description', {
		toolbar : 'Customupload'
	});
    avalon.scan(dom.body);
	vm.bindStatus = Cookie.get("bindStatus");
	vm.supplierErp();
	//vm.wareCategoryList();
	vm.wareBrandList();
	vm.wareUnitList();
	vm.supplierSiteList();
	vm.regionProvinceList();
	vm.wareGetId();
    return vm;
});
